<template>
  <div>
    <!-- table -->
    <!-- 旧件回运查询 - 明细 -->
    <BreakSpace label="通知单信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel1" :list="formList" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="margin-bottom: 1rem"></div>
    <BreakSpace label="上报信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel2" :list="formList2" :cols="3" :formType="'add'" labelWidth="100" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <div style="margin-bottom: 2rem"></div>
    <BreakSpace label="保修旧件列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table1"
      :columns="columns"
      :params="fetchParams"
      :dataSource="dataList"
      :datakey="'items'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      height="auto"
      :isPagination="false"
      :isSelectColumn="true"
    ></FilterTable>
    <div style="margin-bottom: 1rem"></div>
    <BreakSpace label="操作记录" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table2"
      :columns="columns2"
      :params="fetchParams"
      :dataSource="dataList2"
      :datakey="'items'"
      :onColumnsChange="(columns) => (this.columns2 = columns2)"
      :onRowSelectChange="selectChange"
      selectionType="single"
      height="auto"
      :isPagination="false"
      :isSelectColumn="false"
    ></FilterTable>
    <div style="margin-bottom: 1rem"></div>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
<!--      <multiuse-button type="primary" icon="el-icon-printer" @click="printLabel()">打印回运标签</multiuse-button>-->
<!--      <multiuse-button type="primary" icon="el-icon-printer" @click="printCarton()">打印回运箱标</multiuse-button>-->
<!--      <multiuse-button type="primary" icon="el-icon-printer" @click="print()">打印回运清单</multiuse-button>-->
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
    <div style="margin-bottom: 4rem"></div>
    <BaseDialog :visible.sync="visibleSelectByClaim" :title="'保修旧件查看'" destroyOnClose width="950px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <selectByClaim @close="closeSelectByClaim" :rowData="rowData"></selectByClaim>
    </BaseDialog>
    <!-- 打印回运箱标 -->
    <BasePrint ref="templateReturnLabelList" :data="printListLabel" template="templateReturnLabelList" direction="horizontal" />
    <!-- 打印回运标签 -->
    <BasePrint ref="templateReturnCartonList" :data="printListCarton" template="templateReturnCartonList" direction="horizontal" />
    <BasePrint ref="templateReturnList" :data="printList" template="templateReturnList" direction="horizontal" />
    <BasePrint ref="templateWaitReturnLabel" :data="printList" template="templateWaitReturnLabel"/>
    <img id="barcode" style="display: none" />
  </div>
</template>
<script>
import { getListByExample, getPartType } from '@/api/dictionary/index.js';
import selectByClaim from '@/pages/claimDemage/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsReturn/selectByClaim.vue';
import { selectById, printById } from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsReturnQuery';
import { generateLabelList} from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsWaitReturnQuery';
import { generateCarton} from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsWaitReturnQuery';

import { dictionary } from '@/utils/dictMixin';
import JsBarcode from 'jsbarcode';
import {phone} from "@/utils/validate";
export default {
  props: ['rowData','rowDatas'],
  mixins: [dictionary],
  components: {
    selectByClaim,
  },
  data() {
    return {
      dataList: [],
      dataList2: [],
      collapse: false,
      infoId: null,
      columns: this.creatHeader(),
      columns2: this.creatHeader2(),
      // topFilterInit: this.topFilterInitFun(),
      // fetchApi: getUser,
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中服务站
      formList: this.createFormList(),
      formList2: this.createFormList2(),
      visibleSelectByClaim: false,
      saveData: null,
      printList: {
        rows: [],
      },
      printListLabel: {
        rows: [],
      },
      printListCarton: {
        rows: [],
      },
      show: false,
    };
  },
  created() {
    this.chuqi();
    this.chuqi2();
    this.init(this.rowData);
  },
  methods: {
    //打印回运箱标
    async printCarton(){
      console.log(this.rowDatas,'cxcxcxcx')
      let newVar = await generateCarton({returnNo: this.rowDatas.returnNo});
      let rows = newVar.data; // 后台返回为数组，固定返回一条数据不会返回多条,查询条件为会运单号，不会产生多条数据
      console.log(newVar.data,"nnnn");
      //this.printListLabel.rows = newVar.data;
      rows.map((x) => {
        //生成条形码
        console.log("aaa")
        JsBarcode('#barcode', x.qrCode);
        this.$nextTick(function () {//异步 其他执行完了执行
          x.codeUrl = document.getElementById('barcode').src;
        });
        //判断logo
        if (x.appId == "beijing") {
          x.logo = require('@/assets/img/beijing.png');
        } else {
          x.logo = require('@/assets/img/arcfox.png');
        }
        console.log(x.logo,"bbb")
      });

      this.$nextTick(() => {
        console.log(rows,"哈哈")
        for(var i = 0; i < rows[0].boxCounts ; i++) {
          let obj = {...rows[0]};
          obj.number = i + 1;
          this.printListLabel.rows.push(obj);
          console.log(this.printListLabel,"ccc")
        }
        console.log(this.printListLabel,"ddd")
        //调用打印组件
        if(rows[0].boxCounts> 0){
        this.$refs.templateReturnLabelList.EXCUTE_PRINT();

        }else{
        return this.$notify.warning({ title: '提示信息', message: '包装箱数为0，不能打印回运箱标' });
        }

      });

    },
    //打印回运标签
     async printLabel(){
       if (this.selectedRows.length > 0) {
       let id = [];
      // console.log(this.rowData,1234567,this.rowData.claimId)
      this.selectedRows.map(x => {
        id.push(x.claimId);
      })
      let ids =  [...new Set(id)]
      console.log(ids,"ids值")
      const res = await generateLabelList({ids: ids});
      this.printList.rows = res.data;
      this.printList.rows.map((x) => {
        if (x.appId == "beijing") {
          x.logo = require('@/assets/img/beijing.png');
        } else {
          x.logo = require('@/assets/img/arcfox.png');
        }
      })
      this.printList.rows.map((x) => {
        JsBarcode('#barcode', x.codeUrl);
        this.$nextTick(function () {
          x.codeUrl = document.getElementById('barcode').src;
        });
      });
      this.$nextTick(() => {
        this.$refs.templateWaitReturnLabel.EXCUTE_PRINT();
      });
      }else{
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行打印回运标签！' });
      }
    },
  //打印回运清单
  //打印回运清单
    async print() {
      let newVar = await printById({id: this.rowData});
      this.printList = newVar.data;
      this.$nextTick(() => {
        this.$refs.templateReturnList.EXCUTE_PRINT();
      });
    },
    async init(val) {
      let newVar = await selectById({ id: val });
      this.editData = newVar.data;
      console.log('=== 通过ID查询结果返回 ==== ', newVar, ' ======');
      this.pushDtls(newVar.data.dtlList)
      this.formList.forEach((x) => {
        console.log(newVar);
        x.initialValue = newVar.data[x.fieldName];
      });
      this.formList2.forEach((x) => {
        x.initialValue = newVar.data[x.fieldName];
        if (x.fieldName == 'fileList') {
          x.initialValue = newVar.data.fileList.map((f) => ({ name: f.title, url: f.fileUrl }));
        }
      });
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(newVar.data.claimList);
      this.$refs.table2.$refs.pageTable.EXECUTE_INSERT(newVar.data.logList);
    },
    pushDtls(val) {
      let list = [];
      let pageList = this.$refs.table1.$refs.pageTable.list;
      val.map(x => {
        // this.claimIds.push(x.cmsClaimId)
        if (pageList.length == 0) {
          list.push(x);
        } else {
          if(!pageList.find(f => f.cmsClaimId == x.cmsClaimId)) {
            list.push(x);
          }
        }
      });
      // list.map(f =>{
      //   console.log(f.cmsClaimNo);
      // delete f.pestructionCount;
      // delete f.partCount;
      // })
      // this.$refs.table1.$refs.pageTable.EXECUTE_DELETE(this.$refs.table1.$refs.pageTable.list);
      console.log(list);
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(list);
      this.fetchParams = { ...this.fetchParams };
      console.log("claimIds=>", this.claimIds)
    },
    //旧件仓库下拉框
    async chuqi() {
      console.log('===== 获取下拉框数据 ====== ');
      const res = await getListByExample();
      console.log('==========', res);
      if (res.resultCode == 200) {
        this.formList.find((x) => x.fieldName == 'whCode').initialValue = '';
        this.formList.find((x) => x.fieldName == 'whCode').itemList = res.data.map((y) => ({ text: y.whName, value: y.whCode }));
      }
    },
    //运输方式下拉框
    async chuqi2() {
      console.log('===== 获取下拉框数据 ====== ');
      const res = await getPartType({ type: 5521 });
      console.log('==========', res);
      if (res.resultCode == 200) {
        this.formList2.find((x) => x.fieldName == 'expressType').initialValue = '';
        this.formList2.find((x) => x.fieldName == 'expressType').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      }
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    queryByNo(val) {
      this.rowData = val.cmsClaimId;
      console.log('查看明细', this.rowData);
      this.visibleSelectByClaim = true;
    },
    closeSelectByClaim() {
      this.visibleSelectByClaim = false;
    },
    //通知单信息
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '通知单号',
          fieldName: 'returnNo',
          readonly: true,// 只读
          disabled: true // 置会
        },
        {
          type: 'INPUT',
          label: '联系人',
          placeholder: '请输入联系人...',
          rules: [{required: true, message: '请输入联系人....', trigger: 'change'}],
          fieldName: 'conPerson',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT',
          label: '联系电话',
          placeholder: '请输入联系电话...',
          rules: [{required: true, message: '请输入联系电话...', validator: phone ,trigger: 'blur'}],
          fieldName: 'conTel',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'SELECT',
          label: '旧件仓库',
          fieldName: 'whCode',
          placeholder: '请选择旧件仓库...',
          rules: [{required: true, message: '请选择旧件仓库...', trigger: 'change'}],
          itemList: [],
          change: val => {
            this.changeSeriesSelect(val);
          },
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT',
          label: '邮寄地址',
          placeholder: '请输入邮寄地址...',
          rules: [{required: true, message: '请输入邮寄地址...', trigger: 'change'}],
          fieldName: 'expressAddress',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        // {
        //   type: 'INPUT',
        //   label: '邮箱',
        //   placeholder: '请输入邮箱...',
        //   rules: [{ trigger: 'blur', validator: email }],
        //   fieldName: 'email'
        // },
      ];
    },
    //上报信息
    createFormList2() {
      return [
        {
          type: 'SELECT',
          label: '运输方式',
          fieldName: 'expressType',
          rules: [{required: true, message: '请选择运输方式...', trigger: 'change'}],
          placeholder: '请选择运输方式...',
          itemList: [],
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT',
          label: '物流公司',
          placeholder: '请输入物流公司...',
          rules: [{required: true, message: '请输入物流公司...', trigger: 'change'}],
          fieldName: 'expressCompany',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT',
          label: '物流单号',
          placeholder: '请输入物流单号...',
          // rules: [{required: true, message: '请输入物流单号...', trigger: 'change'}],
          fieldName: 'expressNo',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '包装箱数',
          placeholder: '请输入包装箱数...',
          fieldName: 'boxCounts',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '纸箱数量',
          placeholder: '请输入纸箱数量...',
          fieldName: 'paperCounts',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '木箱数量',
          placeholder: '请输入木箱数量...',
          fieldName: 'woodCounts',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '铁箱数量',
          placeholder: '请输入铁箱数量...',
          fieldName: 'ironCounts',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '裸件数量',
          placeholder: '请输入裸件数量...',
          fieldName: 'bareParts',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'DATE',
          label: '发运时间',
          fieldName: 'dlDate',
          valueFormat: 'yyyy-MM-dd', //返回数据格式
          initialValue: '',
          placeholder: '请选择发运时间...',
          style: { width: '100%' },
          rules: [{required: true, message: '请选择发运时间...', trigger: 'change'}],
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'INPUT_NUMBER',
          label: '旧件回运费用',
          placeholder: '请输入旧件回运费用...',
          fieldName: 'freightAmount',
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remarks',
          placeholder: '请输入备注...',
          selfCols: 3,// 元素占据几行
          rows: 3,
          readonly: true, // 只读
          disabled: true, //置灰
        },
        {
          type: 'UPLOAD_FILE',
          label: '查看文件',
          fieldName: 'fileList',
          placeholder: '选择文件...',
          disabled: true, //置灰
          readonly: true, // 只读
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 10,
            tipText: '（支持PDF、RAR、JPG格式）'
          }
        }
      ];
    },
    //保修旧件列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.queryByNo(props.row)}>
                  查看
                </multiuse-button>
              </div>
            );
          },
        },
        {title: '索赔id', dataIndex: 'cmsClaimId', sorter: true, hidden: true},
        // { title: '车辆属性', dataIndex: 'ifComm', sorter: true,filterItems: this.createDictList('5543'),
        //   dictItems: this.createDictList('5543'),
        //   render: props => {
        //     return <span>{this.createDictText(props.row.ifComm, '5543')}</span>;
        //   } },
        {title: '索赔单号', dataIndex: 'cmsClaimNo', sorter: true},
        {title: 'VIN', dataIndex: 'vin', sorter: true, width: 150},
        {title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true},
        // {title: '维修单号', dataIndex: 'roNo', sorter: true},
        {title: '旧件id', dataIndex: 'partId', sorter: true, hidden: true},
        {title: '旧件代码', dataIndex: 'partCode', sorter: true},
        {title: '旧件名称', dataIndex: 'partName', sorter: true},
        {title: '供应商编码', dataIndex: 'supCode', sorter: true},
        // {title: '主损件代码', dataIndex: 'mainPartCode', sorter: true},
        // {title: '主损件名称', dataIndex: 'mainPartName', sorter: true},
        {
          title: '旧件数量',
          dataIndex: 'partCount',
          // minWidth: 90,
          sorter: true,
          // editable: true,
          // defaultEditable: true,
          // showOverflowTooltip: true,
          // editType: 'input'
          width: 100
        },
        {
          title: '回运数量',
          dataIndex: 'actualPartCount',
          render: (props) => {
            return (
              <div style="text-align:center">
                <el-input
                  disabled="true"
                  οnkeyup="value=value.replace(/[^\d]/g,'')"
                  // disabled="true"
                  v-model={props.row.actualPartCount}
                />
              </div>
            );
          },
        },
        {
          title: '装箱属性',
          dataIndex: 'boxAttrStr',
          sorter: true,
          minWidth: 120,
          editable: true,
          defaultEditable: true,
          showOverflowTooltip: true,
          editType: 'select',
          editItems: [],
          disabled: true // 置会
        },
        {
          title: '箱号',
          dataIndex: 'boxNo',
          disabled: true, // 置会
          render: (props) => {
            return (
              <div style="text-align:center">
                <el-input
                  disabled="true"
                  v-model={props.row.boxNo}
                />
              </div>
            );
          },
        }
        // {title: '索赔类型', dataIndex: 'cmsClaimType', sorter: true, hidden: true},
      ];
    },
    //操作记录
    creatHeader2() {
      return [
        { title: '操作人', dataIndex: 'checkByStr', sorter: true },
        { title: '操作时间', dataIndex: 'checkAt', sorter: true },
        // {title: '操作类型', dataIndex: 'checkStatus2', sorter: true},
        { title: '操作后状态', dataIndex: 'statusStr', sorter: true },
        // {title: '操作备注', dataIndex: 'checkRemarks', sorter: true}
      ];
    },
  },
};
</script>

<style lang="less" scoped></style>
